<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form :inline="true" :model="employeeQueryForm" ref="employeeQueryFormRef" :rules="rules">
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="employeeQueryForm.enterpriseName" placeholder="请选择企业名称" readonly="readonly">
            <template #suffix>
              <el-icon @click="findEnterprise"><Search/></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="工号" prop="employeeNumber">
          <el-input v-model="employeeQueryForm.employeeNumber" placeholder="请输入工号" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeQueryForm.name" placeholder="请输入姓名" maxlength="64"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="employeeQueryForm.departmentName" placeholder="请选择部门名称" readonly="readonly">
            <template #suffix>
              <el-icon @click="findDepartment"><Search/></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="岗位名称" prop="positionName">
          <el-input v-model="employeeQueryForm.positionName" placeholder="请选择岗位名称" readonly="readonly">
            <template #suffix>
              <el-icon @click="findPosition"><Search/></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="state.tableData"
        border
        v-loading="state.loading"
        size="small"
        header-cell-class-name="table-header-cell-font"
        cell-class-name="table-cell-font"
        @row-dblclick="employeeSelected">
        <el-table-column prop="enterpriseName" label="企业名称" width="180"></el-table-column>
        <el-table-column prop="employeeNumber" label="工号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="password" label="密码" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别">
          <template v-slot="{ row }">
            <div v-if="row.gender === 1">男</div>
            <div v-if="row.gender === 2">女</div>
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期" width="120"></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="provinceName" label="省"></el-table-column>
        <el-table-column prop="cityName" label="市"></el-table-column>
        <el-table-column prop="areaName" label="区"></el-table-column>
        <el-table-column prop="address" label="家庭地址" width="200"></el-table-column>
        <el-table-column prop="hireDate" label="聘用日期" width="120"></el-table-column>
        <el-table-column prop="departmentName" label="部门名称" width="120"></el-table-column>
        <el-table-column prop="positionName" label="岗位名称" width="120"></el-table-column>
      </el-table>
      <div class="table-pagination">
        <el-pagination
          @current-change="changePage"
          :current-page="state.currentPage"
          :page-sizes="state.pageSizes"
          :page-size="state.pageSize"
          background
          layout="total, prev, pager, next, jumper"
          :total="state.total">
        </el-pagination>
      </div>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="enterpriseSelectorVisible" v-if="enterpriseSelectorVisible" title="企业信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <enterprise-selector @enterprise-selected-event="handleEnterpriseSelectedEvent">
      </enterprise-selector>
    </el-dialog>
    <el-dialog v-model="departmentSelectorVisible" v-if="departmentSelectorVisible" title="部门信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <department-selector @department-selected-event="handleDepartmentSelectedEvent">
      </department-selector>
    </el-dialog>
    <el-dialog v-model="positionSelectorVisible" v-if="positionSelectorVisible" title="岗位信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <position-selector @position-selected-event="handlePositionSelectedEvent">
      </position-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineEmits, inject, onMounted, reactive, ref, toRefs } from 'vue'
import employeeApi from '@/api/employeeApi'
import type {EmployeeQueryForm} from "@/types/req/employeeQueryForm";
import type {Employee} from "@/types/resp/employee";
import {type FormInstance} from "element-plus";
import type {Result} from "@/types/result";
import type {Page} from "@/types/page";
import { Search } from '@element-plus/icons-vue';
import EnterpriseSelector from "@/views/enterprise/EnterpriseSelector.vue";
import DepartmentSelector from "@/views/department/DepartmentSelector.vue";
import PositionSelector from "@/views/position/PositionSelector.vue";

const employeeQueryFormRef = ref<FormInstance | null>(null);
const employeeQueryForm = reactive<EmployeeQueryForm>({
  enterpriseId: 0,
  enterpriseName: '',
  employeeNumber: '',
  name: '',
  departmentId: 0,
  departmentName: '',
  positionId: 0,
  positionName: '',
})
const enterpriseSelectorVisible = ref<boolean>(false)
const departmentSelectorVisible = ref<boolean>(false)
const positionSelectorVisible = ref<boolean>(false)

const state = reactive({
  loading: false,
  tableData: [] as Employee[], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  pageSizes: [10, 20, 50]
})

const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')

const rules = reactive({
});

const emit = defineEmits<{
  (e: 'employeeSelectedEvent', data?: {
    employeeId: number,
    employeeName: string,
    }): void;
}>()

onMounted(() => {
  onSearch()
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
})

const getPageData = async () => {
  try {
    state.loading = true
    const resp: Result<Page<Employee>> = await employeeApi.find(employeeQueryForm)
    if (resp && resp.code === 1) {
      if (resp.data) {
        const page: Page<Employee> = resp.data
        if (page && page.list.length > 0) {
          state.tableData = page.list
          state.total = page.total
        }
      }
    }
  } catch (e) {
    console.log('获取数据异常', e)
  } finally {
    state.loading = false
  }
}
const onSearch = () => {
  getPageData()
}

const changePage = (val: number) => {
  state.currentPage = val
  getPageData()
}

const onReset = () => {
  if (employeeQueryFormRef.value) {
    employeeQueryFormRef.value.resetFields()
  }
  state.currentPage = 1
  getPageData()
}

const employeeSelected = (row: Employee) => {
  emit('employeeSelectedEvent', {
    employeeId: row.id,
    employeeName: row.name,
  })
}

const findEnterprise = () => {
  enterpriseSelectorVisible.value = true
}

const handleEnterpriseSelectedEvent = (selectedEnterprise: any) => {
  enterpriseSelectorVisible.value = false
  if (selectedEnterprise && 'enterpriseId' in selectedEnterprise && employeeQueryForm.enterpriseId !== selectedEnterprise['enterpriseId']) {
    employeeQueryForm.enterpriseId = selectedEnterprise['enterpriseId']
    employeeQueryForm.enterpriseName = selectedEnterprise['enterpriseName']
  }
}
const findDepartment = () => {
  departmentSelectorVisible.value = true
}

const handleDepartmentSelectedEvent = (selectedDepartment: any) => {
  departmentSelectorVisible.value = false
  if (selectedDepartment && 'departmentId' in selectedDepartment && employeeQueryForm.departmentId !== selectedDepartment['departmentId']) {
    employeeQueryForm.departmentId = selectedDepartment['departmentId']
    employeeQueryForm.departmentName = selectedDepartment['departmentName']
  }
}
const findPosition = () => {
  positionSelectorVisible.value = true
}

const handlePositionSelectedEvent = (selectedPosition: any) => {
  positionSelectorVisible.value = false
  if (selectedPosition && 'positionId' in selectedPosition && employeeQueryForm.positionId !== selectedPosition['positionId']) {
    employeeQueryForm.positionId = selectedPosition['positionId']
    employeeQueryForm.positionName = selectedPosition['positionName']
  }
}

const onBack = () => {
  emit('employeeSelectedEvent')
}
</script>

<style lang="scss">
</style>
